<template>
  <!-- 系统设置模块-工作日设置页面1 -->
  <div class="fillcontain bgfff">
    <div class="data-box">
      <el-row class="explain_box pb20">
        <el-col :span="18">&nbsp;</el-col>
        <el-col :span="2" class="text_center">
          <span class="explain_holiDay">节假日</span>
        </el-col>
        <el-col :span="2" class="text_center">
          <span class="explain_workDay">正常</span>
        </el-col>
        <el-col :span="2" class="text_center">
          <p class="explain_monthKnots">
            <el-col :span="6">&nbsp;</el-col>
            <el-col :span="2"><span class="dot">&nbsp;</span></el-col>
            <el-col :span="12"><span class="">月结</span></el-col>
          </p>
        </el-col>
      </el-row>
      <el-row class="year_box">
        <el-col :span="6" class="text_right">
          <i class="el-icon-arrow-left" @click="prevYear"></i>
        </el-col>
        <el-col :span="12" class="text_center">
          <span class="year">{{year}}</span>
        </el-col>
        <el-col :span="6" class="text_left">
          <i class="el-icon-arrow-right" @click="nextYear"></i>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8" class="pr10" v-for="item in everyMonthRanges"
                v-if="everyMonthRanges.length > 0">
          <div class="month_box">
            <div class="month_title">
              <el-row class="pt15 pb15">
                <el-col :span="24" class="text_center"><span class="month">{{item.month}}月</span>
                </el-col>
              </el-row>
            </div>
            <el-calendar v-bind:value="item.date" v-if="reFresh">
              <template
                  slot="dateCell"
                  slot-scope="{date, data}">
                <div v-if="item.month == data.day.split('-')[1]"
                     @click.stop="setOneDay(data.day)">
                  <p :class="(workDays[data.day] == 3 || ((date.getDay() == 0 || date.getDay() ==
                   6) && workDays[data.day] != 1)) ? 'explain_holiDay' : 'explain_workDay'">
                    {{ data.day.split('-').slice(2).join('-') }}
                  </p>
                  <el-row class="set">
                    <el-col :span="24" class="pt5">
                      <span class="dot"
                            v-if="workDays[data.day] == 2">&nbsp;</span>
                    </el-col>
                  </el-row>
                </div>
              </template>
            </el-calendar>
          </div>
        </el-col>
      </el-row>
    </div>
    <!-- 日期设置弹窗 -->
    <el-dialog title="日期设置" :visible.sync="dialogFormVisible" width="35%" center>
      <el-form ref="workDayForm"
               :model="oneWorkDay"
               :rules="oneWorkDayRules"
               label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="日期" prop="time">
              <el-input clearable v-model="oneWorkDay.time" placeholder="日期" readonly></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="类型" prop="type">
              <el-radio-group v-model="oneWorkDay.type">
                <el-radio label="1">正常</el-radio>
                <el-radio label="2">月结</el-radio>
                <el-radio label="3">假期</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="doSaveOrUpdate('workDayForm')">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
  import constant from "@/utils/constant";
  import {doWorkDayEdit, getOneWorkDay, getWorkDayList} from "@/api/setting";

  export default {
    data() {
      return {
        reFresh: true,
        dialogFormVisible: false,
        year: 2020,
        workDays: {}, // 当年的设置数据
        oneWorkDayRules: {
          type: [
            {required: true, message: '请选择类型', trigger: 'change'}
          ]
        },
        oneWorkDay: this.initOneWorkDay(),
        everyMonthRanges: []
      }
    },
    created() {
      this.initData();
    },
    mounted() {
    },
    methods: {
      // 初始化当前年份
      initData() {
        this.year = Number(constant.dateFormat('YYYY', new Date()));
        this.initWorkDayByYear();
      },
      initWorkDayByYear() {
        getWorkDayList(this.year).then(res => {
          if (res.resultCode == constant.SUCCESS && res.data) {
            this.workDays = {};
            res.data.forEach(item => {
              this.workDays[item.time] = item.type;
            });
          }
          this.initMonths();
        }).catch(err => {
          this.initMonths();
        });
      },
      // 根据年份更新每月初始化数据
      initMonths() {
        this.everyMonthRanges = [];
        for (let n = 1; n < 13; n++) {
          const month = constant.prefixInt(Number(n), 2);
          // const range = this.getRangeDate(this.year, month);
          const beginDate = [this.year, month, '01'].join('-');
          this.everyMonthRanges.push({month: month, date: beginDate});
        }
        // 按照月份升序排序
        this.everyMonthRanges.sort((a, b) => Number(a.month) - Number(b.month));
      },
      // 上一年初始化
      prevYear() {
        this.year--;
        this.initWorkDayByYear();
      },
      // 下一年初始化
      nextYear() {
        this.year++;
        this.initWorkDayByYear();
      },
      // 设置某天详情
      setOneDay(day) {
        if (this.workDays[day]) {
          getOneWorkDay(day).then(res => {
            if (res.resultCode == constant.SUCCESS && res.data) {
              this.oneWorkDay = res.data;
            }
          });
        } else {
          this.oneWorkDay = this.initOneWorkDay();
          this.oneWorkDay.time = day;
        }
        this.dialogFormVisible = true;
      },
      // 保存工作日设置
      doSaveOrUpdate(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            this.doSubmit();
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      doSubmit() {
        // 默认值设置
        this.oneWorkDay.busType = 'NB';
        doWorkDayEdit(this.oneWorkDay).then(res => {
          if (res.resultCode == constant.SUCCESS) {
            this.workDays[this.oneWorkDay.time] = this.oneWorkDay.type;
            this.refresh();
            this.dialogFormVisible = false;
            this.$message({
              type: 'success',
              message: '设置成功！'
            });
          }
        });
      },
      // 强制刷新日历
      refresh() {
        this.reFresh = false;
        this.$nextTick(() => {
          this.reFresh = true;
        });
      },
      // 初始化弹框信息
      initOneWorkDay() {
        return {
          id: '',             // id
          status: '',         // 状态
          createId: '',       // 创建人ID
          createTime: '',     // 创建时间
          lastUpdateId: '',   // 更新人ID
          lastUpdateTime: '', // 更新时间
          time: '',           // 日期
          type: '',           // 类型1正常2月结3假期
          busType: 'NB'       // 归属业务类型NB(默认)-POS-CLM
        };
      },
      // <el-calendar :range="getRangeDate('2019', '03')"></el-calendar>
      // 根据年月获取当月初始化时间范围
      getRangeDate(year, month) {
        console.log('year:', year, 'month:', month);
        // 计算开始时间
        const beginDate = this.getLastMonday([year, month, '01'].join('-'));
        // 计算结束时间
        const endDate = this.getNextSunday(this.getEndDayOfMonth(month, year));
        console.log('range:', [beginDate, endDate]);
        return [beginDate, endDate];
      },
      // 根据年月获取当月最后一天的日期
      getEndDayOfMonth: function (month, year) {
        let endDate = '';
        const nextMonth = constant.prefixInt(Number(month) + 1, 2);
        if (nextMonth == '13') {
          endDate = [Number(year) + 1, '01', '01'].join('-');
        } else {
          endDate = [year, nextMonth, '01'].join('-');
        }
        endDate = new Date(new Date(endDate).getTime() - 1 * 86400000);
        endDate = constant.dateFormat("YYYY-mm-dd", endDate);
        return endDate;
      },
      // 获取上一个星期一的日期 [例：2019-12-17]
      getLastMonday(day) {
        let resDate;
        const thisDate = new Date(day);
        const weekday = thisDate.getDay();
        if (weekday == 0) {
          // 6
          const newDate = new Date(thisDate.getTime() - 6 * 86400000);
          resDate = constant.dateFormat("YYYY-mm-dd", newDate);
        } else if (weekday == 1) {
          // yes
          resDate = day;
        } else {
          // weekday - 1
          const newDate = new Date((thisDate.getTime() - (weekday - 1) * 86400000));
          resDate = constant.dateFormat("YYYY-mm-dd", newDate);
        }
        return resDate;
      },
      // 获取下一个星期日的日期 [例：2019-12-17]
      getNextSunday(day) {
        let resDate;
        const thisDate = new Date(day);
        const weekday = thisDate.getDay();
        if (weekday == 0) {
          // yes
          resDate = day;
        } else if (weekday == 1) {
          // 6
          const newDate = new Date(thisDate.getTime() + 6 * 86400000);
          resDate = constant.dateFormat("YYYY-mm-dd", newDate);
        } else {
          // 7 - weekday
          const newDate = new Date(thisDate.getTime() + (7 - weekday) * 86400000);
          resDate = constant.dateFormat("YYYY-mm-dd", newDate);
        }
        return resDate;
      },
    }
  }
</script>
<style lang="less" scoped>
  /* 日历控件 */
  .data-box {
    width: 80%;
    margin: 0 auto;
    padding: 20px;
    // 标识说明
    .explain_holiDay {
      color: #68A3FC;
    }

    .explain_workDay {
      color: #F76868;
    }

    .explain_box {
      .explain_monthKnots {
        color: #666;

        .dot {
          display: block;
          border: 1px solid #F9B248;
          background-color: #F9B248;
          border-radius: 50%;
          text-align: center;
          width: 4px;
          height: 4px;
          margin: 6px auto 0 auto;
        }
      }
    }

    // 年份
    .year_box {
      background-color: #F7F9FA;
      border: 1px solid #EBEFF0;
      padding: 15px 0;

      .year {
        color: #333;
        font-size: 24px;
      }

      .el-icon-arrow-left, .el-icon-arrow-right {
        color: #ccc !important;
        cursor: pointer;
        font-size: 24px;
      }
    }

    // 月份
    .month_box {
      border: 1px solid #EBEFF0;
      margin: 20px 0 0 0;

      .month_title {
        background-color: #F7F9FA;

        .week {
          border-top: 1px solid #EBEFF0;
          border-bottom: 1px solid #EBEFF0;

          span {
            color: #333;
            display: inline-block;
            width: 14.28%;
            text-align: center;
            padding: 15px 0;
          }
        }
      }
    }

    .dot {
      display: block;
      border: 1px solid #F9B248;
      background-color: #F9B248;
      border-radius: 50%;
      text-align: center;
      width: 4px;
      height: 4px;
      margin: 2px auto 0 auto;
    }

    .is-selected_bluce {
      color: #1989FA;
    }

    .is-selected_yellow {
      color: #F9B248;
    }

    /*修改日期默认选中样式*/

    /deep/ .el-calendar-table td.is-selected {
      background-color: #ffffff;
    }
  }
</style>